<?php

namespace App\Http\Controllers\Guard\Article;

use App\Http\Controllers\Common\GuardController;
use App\Models\Article\ArticleClassify;
use App\Models\Article\ArticleInfo;
use App\Models\Constant\Constant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class ArticleInfoController extends GuardController {

    public function lst(Request $request) {
        $classifies = ArticleClassify::pluck('name','id')->toArray();
        try{
            $page = $request->input('page',1);
            $pageSize = $request->input('pageSize',Constant::PAGE_SIZE);
            $title = $request->input('title','');
            $keyWord = $request->input('keyWord','');
            $classifyId = $request->input('classifyId','all');
            $createdAt = $request->input('createdAt',[]);
            $conditions = compact('keyWord','classifyId','title','createdAt');
            $conditions['orderBy']['col'] = 'sort';
            $conditions['orderBy']['sort'] = 'desc';

            //dd($conditions);

            $records = (new ArticleInfo)->getLst($conditions)->paginate($pageSize,['*'],'page',$page);
            foreach ($records as $record) {
                $record->description = Str::limit($record->description,20);
                $record->content = Str::limit($record->content,20);
                $record->classify_name = $classifies[$record->classify_id]??'未知';
            }
            return responseSuccess($records->items(),$records->total());
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }
    }

    public function add(Request $request) {
        try{
            DB::beginTransaction();
            $id = $request->input('id',0);
            $info = $request->input();

            $this->validate($request, [
                'title'=>'required|min:1|max:255',
                'classify_id'=>'required'
            ],[],[]);
            if(is_array($info['classify_id'])){
                $info['classify_id'] = array_pop($info['classify_id']);
            }
            $info['sign'] = Str::replace(',', '，', $info['sign']);
            $info['key_word'] = Str::replace(',', '，', $info['key_word']);
            $info['year'] = date('Y');
            $info['month'] = date('m');

            ArticleInfo::updateOrCreate(compact('id'),$info);
            DB::commit();
            return responseSuccess();
        }catch(\Exception $e){
            DB::rollBack();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return responseFail($tip);
        }
    }

    public function change(Request $request) {
        $ids = $request->input('ids',[]);

        if($request->has('status')){
            $status = $request->input('status');
            return $this->changeColByIds(ArticleInfo::class, $ids, compact('status'));
        }
        if($request->has('is_top')){
            $is_top = $request->input('is_top');
            return $this->changeColByIds(ArticleInfo::class, $ids, compact('is_top'));
        }
        return responseSuccess();

    }

    public function detail(Request $request) {
        $ids = $request->input('ids',[]);
        return $this->getRecordByIds(ArticleInfo::class, $ids); // TODO: Change the autogenerated stub
    }

    public function del(Request $request) {
        $ids = $request->input('ids',[]);
        return $this->delRecords(ArticleInfo::class,$ids);
    }

    public function uploadVideo(Request $request) {
        $fileKeys = array_keys($request->file());
        foreach ($fileKeys as $fileKey) {
            $file = $request->file($fileKey);
            $ext = $file->getClientOriginalExtension();
            $middlePath = "/article/".date('Y-m-d');
            $absDir = Storage::disk('upload')->path($middlePath);
            if(!is_dir($absDir)){mkdir($absDir,0777,true);}
            $fileName = time().uniqid().".$ext";
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
            $filePath = '/storage/upload/'.$filePath;
            $info= [
                'url'=>asset($filePath),
            ];
            return response()->json([
                'data'=>$info,
                'errno'=>0
            ]);
        }
    }

    public function uploadImg(Request $request) {
        $fileKeys = array_keys($request->file());
        $info = [];
        foreach ($fileKeys as $fileKey) {
            $file = $request->file($fileKey);
            $ext = $file->getClientOriginalExtension();
            $middlePath = "/article/".date('Y-m-d');
            $absDir = Storage::disk('upload')->path($middlePath);
            if(!is_dir($absDir)){mkdir($absDir,0777,true);}
            $fileName = time().uniqid().".$ext";
            $filePath = $file->storeAs($middlePath,$fileName,'upload');
            $filePath = '/storage/upload/'.$filePath;
            $info[] = [
                'url'=>asset($filePath),
                'atl'=>'图片',
                'href'=>''
            ];

        }
        return response()->json([
            'data'=>$info,
            'errno'=>0
        ]);

    }

}
